from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from goods.models import SKU, GoodsCategory, SPUSpecification, SPU
from meiduo_admin.serializers.skus import SkusSerializer, GoodsCategorySerializer, SPUSpecificationSerializer

from meiduo_admin.utils import PageNumberPagination, PageNum


class SkusView(ModelViewSet):
    # 指定序列化器
    serializer_class = SkusSerializer

    # 指定分页器
    pagination_class = PageNum
    # 认证
    permission_classes = [IsAdminUser]

    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword is None or keyword == '':
            return SKU.objects.all()
        else:
            return SKU.objects.filter(name__contains=keyword)

    @action(methods=['get'], detail=False)
    def categories(self, request):

        data = GoodsCategory.objects.filter(subs=None)

        ser = GoodsCategorySerializer(data, many=True)

        return Response(ser.data)

    def simple(self, request, pk):
        try:
            spu = SPU.objects.get(id=pk)
        except:
            return Response({'error': '商品不存在'}, status=400)

        specs_data = spu.specs
        ser = SPUSpecificationSerializer(specs_data, many=True)
        return Response(ser.data)
